package com.dayanxs.Service;

import com.dayanxs.Utils.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

@Service
public class FileUploadService {

    private static final String UPLOAD_DIR = "uploads/"; // 相对路径，相对于项目的运行目录

    public String uploadImage(MultipartFile file) throws IOException {
        // 获取当前工作目录
        File currentDir = new File(System.getProperty("user.dir")); // 当前工作目录
        File uploadDir = new File(currentDir, UPLOAD_DIR);

        // 检查目录是否存在
        if (!uploadDir.exists()) {
            uploadDir.mkdirs(); // 创建目录
        }

        // 获取文件名和扩展名
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            throw new IllegalArgumentException("Invalid file name");
        }

        String extension = getFileExtension(fileName);
        if (!isAllowedExtension(extension)) {
            throw new IllegalArgumentException("Invalid file extension");
        }

        // 重命名文件
        String newFileName = UUID.randomUUID().toString() + "." + extension;
        File uploadFile = new File(uploadDir, newFileName);

        // 保存文件
        file.transferTo(uploadFile);

        return "/uploads/" + newFileName; // 返回相对路径，适合 HTTP 请求
    }

    private boolean isAllowedExtension(String extension) {
        return Arrays.asList("png", "jpg", "jpeg", "webp", "gif", "bmp").contains(extension.toLowerCase());
    }

    private String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex >= 0 ? fileName.substring(lastDotIndex + 1).toLowerCase() : "";
    }
}
